package top.songxs.gmall.rabbit.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTemplateConfiguration {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {

        // 创建rabbitTemplate对象
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        // 设置confirmCallBack
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息成功发送给了交换机....");
            } else {
                System.out.println("消息没有成功发送给交换机....");
            }
        });

        // 设置returnCallBack
        rabbitTemplate.setMandatory(true);  // 将发送失败的消息再次发给生产者
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) ->
                System.out.println("消息正常发送给交换机" + exchange + "，但是没有发送给队列 ---->routingKey：" + routingKey));
        // 返回
        return rabbitTemplate;

    }
}
